package com.hundsun.documentripper.controller;

import com.hundsun.documentripper.domain.other.word.StyleInfo;
import com.hundsun.documentripper.domain.other.word.WordBuildInfo;
import com.hundsun.documentripper.domain.pojo.File;
import com.hundsun.documentripper.domain.pojo.FileNode;
import com.hundsun.documentripper.domain.pojo.NodeContent;
import com.hundsun.documentripper.domain.pojo.NodeTemplateField;
import com.hundsun.documentripper.service.FileNodeService;
import com.hundsun.documentripper.service.FileService;
import com.hundsun.documentripper.service.NodeContentService;
import com.hundsun.documentripper.service.NodeTemplateFieldService;
import com.hundsun.documentripper.utils.HtmlToWordUtil;
import com.hundsun.documentripper.utils.StringUtil;
import io.swagger.annotations.Api;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.OutputStream;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;

/**
 * 导出
 */
@Api("导出")
@RestController
public class ExportController {

    @Autowired
    private FileService fileService;

    @Autowired
    private FileNodeService fileNodeService;

    @Autowired
    private NodeContentService nodeContentService;

    @Autowired
    private NodeTemplateFieldService nodeTemplateFieldService;

    @GetMapping("/export/word")
    public void exportWord(@RequestParam("uuid") String uuid, HttpServletResponse response) throws Exception {
        try (OutputStream outputStream = response.getOutputStream()) {
            List<WordBuildInfo> wordBuildInfoList = new ArrayList<>();
            File file = fileService.getFileById(uuid);
            //查询该文件的节点内容
            List<FileNode> fileNodeTemps = fileNodeService.getFileNodeListById(uuid);
            //排序成树状列表
            List<FileNode> fileNodes = SortTreeDataByNodes(fileNodeTemps);
            if (StringUtil.isNotEmpty(fileNodes)) {
                for (FileNode fileNode : fileNodes) {
                    WordBuildInfo titleInfoNode = new WordBuildInfo();
                    titleInfoNode.setTitle(fileNode.getNodeValue());
                    titleInfoNode.setTitleStyle(getTitleStyle(fileNode.getFileNodeTemplateUuid()));
                    titleInfoNode.setContent(getContent(fileNode.getContentUuid()));
                    titleInfoNode.setContentStyle(getTitleStyle(fileNode.getContentNodeTemplateUuid()));
                    wordBuildInfoList.add(titleInfoNode);
                }
                String content = HtmlToWordUtil.buildHtml(wordBuildInfoList);
                response.setCharacterEncoding(StandardCharsets.UTF_8.name());
                response.setContentType("application/msword");
                response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + new String((file.getName() + ".doc").getBytes(StandardCharsets.UTF_8), "ISO8859-1"));
                outputStream.write(content.getBytes(StandardCharsets.UTF_8));
                outputStream.flush();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 将节点数据排序成树状
     *
     * @param fileNodeTemps
     */
    private List<FileNode> SortTreeDataByNodes(List<FileNode> fileNodeTemps) {
        List<FileNode> fileNodes = new ArrayList<>();
        List<String> okStr = new ArrayList<>();
        boolean flag = true;
        while (flag) {
            for (FileNode fileNode : fileNodeTemps) {
                if ((StringUtil.isBlank(fileNode.getParentUuid()) || okStr.contains(fileNode.getParentUuid()))
                        && !okStr.contains(fileNode.getUuid())) {
                    fileNodes.add(fileNode);
                    okStr.add(fileNode.getUuid());
                }
                if (okStr.size() >= fileNodeTemps.size()) {
                    flag = false;
                    break;
                }
            }
        }
        return fileNodes;
    }

    /**
     * 获取节点样式
     *
     * @param fileNodeTemplateUuid
     * @return
     */
    private List<StyleInfo> getTitleStyle(String fileNodeTemplateUuid) {
        List<StyleInfo> styleInfos = new ArrayList<>();
        List<NodeTemplateField> nodeTemplateFields = nodeTemplateFieldService.getNodeTemplateFieldListById(fileNodeTemplateUuid);
        if (StringUtil.isNotEmpty(nodeTemplateFields)) {
            for (NodeTemplateField nodeTemplateField : nodeTemplateFields) {
                StyleInfo styleInfo = new StyleInfo();
                styleInfo.setStyleKey(nodeTemplateField.getType());
                styleInfo.setStyleValue(nodeTemplateField.getValue());
                styleInfos.add(styleInfo);
            }
        }
        return styleInfos;
    }

    /**
     * 获取正文内容
     *
     * @param contentUuid
     * @return
     */
    private String getContent(String contentUuid) {
        NodeContent nodeContent = nodeContentService.getNodeContent(contentUuid);
        if (StringUtil.isNotNull(nodeContent)) {
            return nodeContent.getValue();
        }
        return "";
    }
}
